package backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Function;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class solveNQueens {
    List<List<String>> result = new ArrayList<>();
    char[][] chessboard;
    public List<List<String>> solveNQueens(int n) {
        chessboard = new char[n][n];
        for (char[] temp : chessboard){
            Arrays.fill(temp, '.');
        }
        backtracking(chessboard, 0, n);
        return result;
    }
    public void backtracking(char[][] chessboard, int row, int n){
        if (row == n){
            result.add(Array2List(chessboard));
        }
        for (int i = 0; i < n; i++) {
            if (isValid(chessboard, row, i, n)){
                chessboard[row][i] = 'Q';
                backtracking(chessboard, row + 1, n);
                chessboard[row][i] = '.';
            }
        }
    }
    public boolean isValid(char[][] chessboard, int row, int col, int n){
        for (int j = 0; j < row; j++) {
            if (chessboard[j][col] == ('Q')){
                return false;
            }
        }
        for (int j = row - 1, k = col - 1; j >= 0 && k >= 0; j--, k--){
            if (chessboard[j][k] == ('Q')){
                return false;
            }
        }
        for (int j = row - 1, k = col + 1; j >= 0 && k < n; j--, k++){
            if (chessboard[j][k] == ('Q')){
                return false;
            }
        }
        return true;
    }
    public List<String> Array2List(char[][] chessboard) {
        List<String> list = new ArrayList<>();

        for (char[] c : chessboard) {
            list.add(String.copyValueOf(c));
        }
        return list;
    }
}
